<template>
  <div :style="{ width, height }" ref="chartRef"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import echarts, { ECOption } from "@/utils/echarts";
import merge from "lodash/merge";
import cloneDeep from "lodash/cloneDeep";
import commonOption from "./commonOption";

defineOptions({
  name: "Chart",
});

const props = withDefaults(
  defineProps<{
    width?: string;
    height?: string;
    option: ECOption;
  }>(),
  {
    width: "100%",
    height: "100%",
  }
);

const chartRef = ref<HTMLDivElement>();

let myChart: echarts.ECharts;

const initEcharts = () => {
  myChart = echarts.init(chartRef.value);
  // commonOption props.option
  myChart.setOption(merge(cloneDeep(commonOption), props.option));
};

// 监视option变化，重新渲染图表
watch(props.option, () => {
  myChart.setOption(merge(cloneDeep(commonOption), props.option));
});

const resizeEcharts = () => {
  myChart.resize(); // 当浏览器大小发生变化，重新调整图表大小
};

onMounted(() => {
  initEcharts();
  window.addEventListener("resize", resizeEcharts);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeEcharts);
});
</script>

<style scoped lang="scss"></style>
